package com.abing.core.utils;

import com.abing.base.BaseApiService;
import com.abing.base.BaseResponse;
import org.springframework.retry.RecoveryCallback;
import org.springframework.retry.RetryContext;
import org.springframework.retry.backoff.ExponentialBackOffPolicy;
import org.springframework.retry.policy.SimpleRetryPolicy;
import org.springframework.retry.support.RetryTemplate;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.function.Consumer;

/**
 * @author : liubing
 * @date : 2021/5/14 19:36
 */
public class RetryUtilsV2 {

//    public static void main(String[] args) {
//        String error = RetryUtilsV2.invoke(() -> {
//            // 返回数据的代码编写
//            // return "test";
//            throw new RuntimeException("error");
//        }, throwable -> System.out.println("error"), 3, 5_000, new ArrayList<>());
//        // 输出返回数据
//        System.out.println(error);
//        String error = RetryUtilsV2.invoke(() -> {
//            // 返回数据的代码编写
//            // return "test";
//            throw new RuntimeException("error");
//        },throwable -> System.out.println("error"),3, 5_000, new ArrayList<>());
//    }
    /**
     * 重试调度方法
     *
     * @param dataSupplier
     * 		返回数据方法执行体
     * @param exceptionCaught
     * 		出错异常处理(包括第一次执行和重试错误)
     * @param retryCount
     * 		重试次数
     * @param sleepTime
     * 		重试间隔睡眠时间(注意：阻塞当前线程)
     * @param expectExceptions
     * 		期待异常(抛出符合相应异常时候重试),空或者空容器默认进行重试
     * @param <R>
     * 		数据类型
     *
     * @return R
     */
    public static <R> R invoke(Supplier<R> dataSupplier,
                               Consumer<Throwable> exceptionCaught,
                               int retryCount,
                               long sleepTime,
                               List<Class<? extends Throwable>> expectExceptions) {
        Throwable ex;
        try {
            // 产生数据
            return dataSupplier == null ? null : dataSupplier.get();
        } catch (Throwable throwable) {
            // 捕获异常
            catchException(exceptionCaught, throwable);
            ex = throwable;
        }

        if (expectExceptions != null && !expectExceptions.isEmpty()) {
            // 校验异常是否匹配期待异常
            Class<? extends Throwable> exClass = ex.getClass();
            boolean match = expectExceptions.stream().anyMatch(clazz -> clazz == exClass);
            if (!match) {
                return null;
            }
        }

        // 匹配期待异常或者允许任何异常重试
        for (int i = 0; i < retryCount; i++) {
            try {
                if (sleepTime > 0) {
                    Thread.sleep(sleepTime);
                }
                return dataSupplier.get();
            } catch (InterruptedException e) {
                System.err.println("thread interrupted !! break retry,cause:" + e.getMessage());
                // 恢复中断信号
                Thread.currentThread().interrupt();
                // 线程中断直接退出重试
                break;
            } catch (Throwable throwable) {
                catchException(exceptionCaught, throwable);
            }
        }

        return null;
    }

    private static void catchException(Consumer<Throwable> exceptionCaught, Throwable throwable) {
        try {
            if (exceptionCaught != null) {
                exceptionCaught.accept(throwable);
            }
        } catch (Throwable e) {
            System.err.println("retry exception caught throw exception:" + e.getMessage());
        }
    }

    /**
     * 函数式接口可以抛出异常
     *
     * @param <T>
     */
    @FunctionalInterface
    public interface Supplier<T> {

        /**
         * Gets a result.
         *
         * @return a result
         *
         * @throws Exception 错误时候抛出异常
         */
        T get() throws Exception;
    }


    public static <R> R invokeV2(Supplier<R> dataSupplier,
                               int maxAttempts,
                               long initialInterval,
                               int multiplier) throws Exception {

        RetryTemplate template = new RetryTemplate();
        // 策略
        SimpleRetryPolicy policy = new SimpleRetryPolicy();
        //最大重试次数
        policy.setMaxAttempts(maxAttempts);
        template.setRetryPolicy(policy);

        ExponentialBackOffPolicy exponen = new ExponentialBackOffPolicy();
        //初始时间间隔
        exponen.setInitialInterval(initialInterval);
        //每次重试间隔倍数
        exponen.setMultiplier(multiplier);
        template.setBackOffPolicy(exponen);
        return (R) template.execute(arg0 -> {
            // 产生数据
            return dataSupplier.get();
        }, context -> new BaseApiService().setResultError(context.getLastThrowable().getMessage()));

    }

    public static void main(String[] args) throws Exception{
        BaseResponse error = RetryUtilsV2.invokeV2(() -> {
            // 返回数据的代码编写
            return println();
        },3, 3000,2);
        System.out.println(error);
    }
    private static BaseResponse println() throws Exception {
        System.out.println(DateUtils.formatDateTime(new Date()) + "---123");
        Thread.sleep(3000);
        throw new Exception("111");
    }
}
